var express = require('express');
var router = express.Router();

//数据库
var User = require(__dirname + '/../models/user.js');
var Location = require(__dirname + '/../models/location.js');

var gwxk = require(__dirname + '/../lib/gwxk.lib.js');
var redis = require(__dirname + '/../lib/redis.js');
var G = new gwxk();
/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('users-index');
});

//用户登录
router.post('/login', function(req, res, next) {
  var $user = req.body.username;
  var $password = req.body.password;
  var op = {
    username:$user,
    password:$password
  };
  G.login(op, function (data) {
    "use strict";
    if(data.status){
      var token = md5($user+new Date().toString());
      User.findOne($user)
      .then((re)=>{
        if(!re){
          User.save({stu_number:$user, username:data.data.name})
          .catch((err) => console.warn(err));
        }
      });
      redis.setToken(token, $user)
          .then(function () {
            data.data.token = token;
            res.json(data);
          })
          .catch((err)=>{
            console.warn(err);
          })
    }
    else{
      res.json(data);
    }
  });

});

//定位数据上传 one by one
router.post('/upload_location', function (req, res, next) {
  "use strict";
  var token = req.body.token;
  redis.getToken(token)
  .then((username)=>{
    var data = {
      stu_number: username,
      location_x: req.body.location_x,
      location_y: req.body.location_y,
      msg: req.body.msg
    };

    if(req.body.s_id){
      Location.update(req.body.s_id, data)
      .then(()=>{
        res.json({status: 1});
      })
      .catch(()=>{
        res.json({status: 0});
      });
    }
    else{
      Location.save(data)
          .then(()=>{
            res.json({status: 1});
          })
          .catch(()=>{
            res.json({status: 0});
          });
    }

  })
  .catch((err)=>{
    var re = {
      status: 0,
      info: 'token 错误'
    };
    console.warn(err);
    res.json(re);
  });
});

//定位数据下载 All
router.get("/download_location", function (req, res, next) {
  var token = req.query.token;
  redis.getToken(token)
      .then((username)=>{
        "use strict";
        Location.findAll(username)
        .then((re)=>{
          var data = {
            status: 1,
            len: re.length,
            data: re
          };

          res.json(data);
        })
        .catch((err)=>{
          console.warn(err);
          res.json({status:0, info: 'data null'});
        });
      })
      .catch((err)=>{
        var re = {
          status: 0,
          info: 'token 错误'
        };
        console.warn(err);
        res.json(re);
      });
});

function md5(data) {
  var Buffer = require("buffer").Buffer;
  var buf = new Buffer(data);
  var str = buf.toString("binary");
  var crypto = require("crypto");
  return crypto.createHash("md5").update(str).digest("hex");
}

module.exports = router;
